package com.dao.utils;

import com.model.JobInfo;
import org.assertj.core.util.Strings;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class JobInfoPredicate {
    private CriteriaBuilder cb;
    private Root<JobInfo> root;
    private List<Predicate> predicates;

    public JobInfoPredicate(Root<JobInfo> root, CriteriaBuilder cb) {
        this.root = root;
        this.cb = cb;
        predicates = new ArrayList<>();
    }

    public JobInfoPredicate(Root<JobInfo> root, CriteriaBuilder cb, int count) {
        this.root = root;
        this.cb = cb;
        predicates = new ArrayList(count);
    }

    public JobInfoPredicate betweenTime(String startDate, String endDate) {
        if(Strings.isNullOrEmpty(startDate) || Strings.isNullOrEmpty(endDate)) return this;
        predicates.add(cb.between(root.get(JobInfo.Fields.releaseDate).as(LocalDate.class),
                LocalDate.parse(startDate), LocalDate.parse(endDate)));
        return this;
    }

    public JobInfoPredicate likeTitle(String title) {
        if(Strings.isNullOrEmpty(title)) return this;
        predicates.add(cb.like(root.get(JobInfo.Fields.recruitTitle), "%" + title + "%"));
        return this;
    }

    public JobInfoPredicate eqReptileClass(String reptileClass) {
        if(Strings.isNullOrEmpty(reptileClass)) return this;
        predicates.add(cb.equal(root.get(JobInfo.Fields.reptileClass), reptileClass));
        return this;
    }

    public JobInfoPredicate eqJobType(String jopType) {
        if(Strings.isNullOrEmpty(jopType)) return this;
        predicates.add(cb.equal(root.get(JobInfo.Fields.jobType), jopType));
        return this;
    }

    public Predicate setPredicate() {
        if(predicates.size() > 0) {
            Predicate[] p = new Predicate[predicates.size()];
            return cb.and(predicates.toArray(p));
        }else {
            return null;
        }
    }

    public Predicate[] getPredicate() {
        Predicate[] p = new Predicate[predicates.size()];
        if(predicates != null && predicates.size() > 0) {
            return predicates.toArray(p);
        }else {
            return p;
        }
    }
}
